<template>
    <div style="width: 1024px;height: 768px;">
        <button
            style="position: fixed;left: 384px;width: 200px;height: 50px;background-color: rgb(23, 93, 255);color: white;font-size: 30px;"
            @click="openPop">{{ pageData.btnText }}</button>
        <a-button type="outline" status="success"
            style="font-size: 20px;margin-left: 10px;cursor: default;position: fixed;">{{
                    dataForm.type === 0 ? "初检" : "复检"
            }}</a-button>
        <div style="cursor: default;position: fixed;left: 760px;z-index: 1;">
            <a-button type="primary" status="success" @click="saveHandler" size="large"
                style="font-size: 20px;margin-right:15px;" :disabled="!pageData.isSave">保存</a-button>
            <a-button type="primary" status="warning" @click="repairHandler" size="large"
                style="font-size: 20px;margin-right:15px;" :disabled="!pageData.isXb">修补</a-button>
            <a-button type="primary" status="danger" @click="downgradeHandler" size="large" style="font-size: 20px;"
                :disabled="!pageData.isJd">降等
            </a-button>
        </div>

        <div class="bg-container" style="margin-top: 30px;">
            <div v-if="isShow">
                <a-form size="small" :model="dataForm" layout="horizontal" label-align="right"
                    :label-col-props="{ span: 11 }" :wrapper-col-props="{ span: 13 }">
                    <a-row :gutter="16">
                        <a-col :span="6">
                            <a-form-item label="布飞条码" :rules="[{ required: true, message: '布飞条码必扫' }]"
                                :validate-trigger="['change', 'blur']">
                                <a-input v-model="dataForm.form.clothCode" ref="getFocus" @change="changeTm"
                                    :disabled="!pageData.isScan" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="验布等级">
                                <a-select popup-container="html"  :loading="loading" @search="handleSearch"
                                    v-model="dataForm.form.perchingGrade" :filter-option="false" allow-search
                                    allow-clear @focus="focusSel">
                                    <a-option v-for="item in pageData.perchingGradeList"
                                        :value="item['verifyclothLevel']">
                                        {{
                                                item["verifyclothLevel"]
                                        }}</a-option>
                                </a-select>
                                <!-- 
                            <a-select popup-container="html"  placeholder="请选择验布等级" v-model="dataForm.form.perchingGrade">
                                <a-option v-for="item in pageData.perchingGradeList" :value="item['verifyclothLevel']">
                                    {{
                                            item["verifyclothLevel"]
                                    }}</a-option>
                            </a-select> -->
                                <!-- <a-input placeholder="请输入验布等级" v-model="pageData.perchingGradeRemark" disabled /> -->
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="检验单号">
                                <a-input v-model="dataForm.form.billNumber" disabled />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="检验日期">
                                <a-date-picker  popup-container="html"  v-model="dataForm.form.billDate" disabled />
                            </a-form-item>

                        </a-col>
                       

                    </a-row>
                    <a-row :gutter="16">
                        <a-col :span="6">
                            <a-form-item label="织造序号">
                                <a-input v-model="dataForm.form.weavingSerialNumber" disabled />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="机台号">
                                <a-input v-model="dataForm.form.machine" disabled />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="匹号">
                                <a-input v-model="dataForm.form.horses" disabled />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="验布等级备注">
                                <a-input v-model="dataForm.form.perchingGradeRemark" disabled />
                            </a-form-item>
                        </a-col>
                        

                    </a-row>
                    <a-row :gutter="16">
                    <a-col :span="6">
                            <a-form-item label="颜色">
                                <a-input v-model="dataForm.form.colour" disabled />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="客户">
                                <a-input v-model="dataForm.form.client" disabled />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="落布重量">
                                <a-input v-model="dataForm.form.croppingWeight" disabled />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="次布分摊重量">
                                <a-input v-model="dataForm.form.timeClothShareWeight" disabled />
                            </a-form-item>
                        </a-col>
                    </a-row>
                    <a-row :gutter="16">
                        <a-col :span="6">
                            <a-form-item label="验后重量">
                                <a-input v-model="dataForm.form.posteriorWeight" disabled />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="坯布编码">
                                <a-input v-model="dataForm.form.greyCode" disabled />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="坯布名称">
                                <a-input v-model="dataForm.form.greigeName" disabled />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6">
                            <a-form-item label="纱批号">
                                <a-input v-model="dataForm.form.yarnBatchNumber" disabled />
                            </a-form-item>
                        </a-col>
                      
                    </a-row>
                    <a-row :gutter="16">
                    <a-col :span="6">
                            <a-form-item label="大布号">
                                <!-- <a-input placeholder="请输入大布号" v-model="dataForm.form.bigClothMark" disabled /> -->
                                <a-select popup-container="html"  v-model="dataForm.form.bigClothMark">
                                    <a-option v-for="item in dataForm.yg" :value="item['bigClothMark']">
                                        {{
                                                item["bigClothMark"]
                                        }}</a-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="6" v-if="dataForm.type === 0">
                            <a-form-item label="验布员" :rules="[{ required: true, message: '验布员必扫' }]"
                                :validate-trigger="['change', 'blur']">
                                <a-input v-model="pageData.clothInspectorOne" disabled />
                                <!-- <a-modal v-model:visible="visible" title="请选择验布员" @cancel="handleCancel"
                                @before-ok="handleBeforeOk">
                                <div style="background-color:#E8F3FF;color: #165DFF;height: 100px;margin-bottom: 10px;line-height: 100px;text-align: center;font-size: 30px;cursor: pointer;"
                                    :default-checked="true">张三</div>
                                <div style="background-color:#E8F3FF;color: #165DFF;height: 100px;line-height: 100px;text-align: center;font-size: 30px;cursor: pointer;"
                                    :default-checked="true">索隆</div>
                            </a-modal> -->
                            </a-form-item>
                        </a-col>
                        <a-col :span="6" v-if="dataForm.type === 1">
                            <a-form-item label="班长复检" :rules="[{ required: true, message: '班长必扫' }]"
                                :validate-trigger="['change', 'blur']">
                                <a-input v-model="pageData.monitorRetest" disabled />
                            </a-form-item>
                        </a-col>
                        <a-col :span="6" v-if="dataForm.type === 1">
                            <a-form-item label="复检日期" :rules="[{ required: true, message: '日期必选' }]"
                                :validate-trigger="['change', 'blur']">
                                <a-date-picker  popup-container="html"  v-model="pageData.retestDate" style="width: 200px;" />
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
            <!-- <div style="text-align: right;">
            <Toolbar :items="['保存', '修补', '降等']" @saveData="saveHandler" @repairData="repairHandler"
                @downgradeData="downgradeHandler">
            </Toolbar>
        </div> -->
        </div>


        <div ref="tablediv" style=" box-sizing: border-box;height:100%;background-color: white;">
            <div style="color: rgb(88,149,253);font-size: 20px;display: inline-block;">疵点项目</div>
            <div style="float:right;display: inline-block;">
                <a-button type="primary" @click="viewHistory" size="large" style="font-size: 20px;"
                    :disabled="!pageData.isLook">查看历史</a-button>
            </div>
            <div style="height: 300px;overflow: auto;border: 1px solid #ccc;width:1024px;box-sizing: border-box;">
                <a-tag v-for="(item, index) of pageData.defectNameList" @click="handleClick(item['defectName'])"
                    :class="{ active: (pageData.defectOb.includes(item['defectName']) || pageData.clickDefectOb.includes(item['defectName'])) }"
                    :key="index"
                    style="margin-left:10px;margin-bottom:10px;height:65px;line-height: 65px;cursor: pointer;width: 120px;font-size: 18px;justify-content: center;background-color: #00B42A;color: white;">
                    {{
                            item['defectName']
                    }}</a-tag>

                <a-modal v-model:visible="visible" title=" " @cancel="handleCancel" @before-ok="handleBeforeOk"
                    :hide-cancel="true" :draggable="true" :footer="false">
                    <!-- <a-tag checkable color="arcoblue" :default-checked="true"  v-for="item in pageData.ygList" >{{item["name"]}}</a-tag> -->
                    <div style="background-color:#E8F3FF;color: #165DFF;height: 100px;margin-bottom: 10px;line-height: 100px;text-align: center;font-size: 35px;cursor: pointer;"
                        :default-checked="true" @click="clickName(item['checkStaff'], item['checkStaffCode'])"
                        v-for="(item, index) in dataForm.ygNameList" :key="index">{{ item["checkStaff"] }}</div>
                    <!-- <div style="background-color:#E8F3FF;color: #165DFF;height: 100px;line-height: 100px;text-align: center;font-size: 30px;cursor: pointer;"
                    :default-checked="true">索隆</div> -->
                </a-modal>
            </div>
            <div style="width:100%;">
                <a-form size="small" :model="pageData" layout="inline">
                    <a-form-item label="总转数">
                        <a-input v-model="dataForm.totalRevolutions" />
                    </a-form-item>
                    <a-form-item label="交班转数">
                        <a-input v-model="dataForm.numberShifts" />
                    </a-form-item>
                    <a-form-item label="坯布状态">
                        <a-select popup-container="html"  v-model="dataForm.checkoutState">
                            <a-option :value="0">待修补</a-option>
                            <a-option :value="1">修补中</a-option>
                            <a-option :value="2">待降级</a-option>
                            <a-option :value="3">通过</a-option>
                        </a-select>
                        <!-- <a-input placeholder="请输入坯布状态" v-model="pageData.greyClothCondition" /> -->
                    </a-form-item>
                    <a-form-item label="复检不合格是否入次布仓：">
                        <a-checkbox style="margin-right:5px;" :default-checked="true" @change="changeClothWarehouse">
                        </a-checkbox>
                        <a-select popup-container="html"  :loading="loading1" @search="handleSearch1" v-model="pageData.dropDownData1"
                            :filter-option="false" allow-search allow-clear @focus="focusSel1">
                            <a-option v-for="item in pageData.getCkList" :value="item['warehouseName']">{{
                                    item["warehouseName"]
                            }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="">
                        <span style="color: red;">*1、点击疵点选择员工</span>
                    </a-form-item>
                </a-form>
                <div style="height: 200px;overflow: auto;display: inline-block;width: 510px;">
                    <a-table stripe :bordered="true" :columns="tableColumnsYg" v-model:selected-keys="s"
                        :loading="table.tableLoading" :data="dataForm.yg" :rowKey="rowKey" size="mini">
                        <template #edit="{ record }">
                            <!-- <a-button type="primary" size="small" status="warning" @click="editHandler(record)">
                            <template #icon>
                                <icon-edit />
                            </template>
                            修 改
                        </a-button> -->
                        </template>
                    </a-table>
                </div>
                <div style="width:100%;display: inline-block;width: 510px;vertical-align: top;">
                <a-table stripe :bordered="true" :columns="tableColumnsCk" v-model:selected-keys="s"
                    :loading="table.tableLoading" :data="dataForm.ckList" :rowKey="rowKey"  size="mini">
                    <template #defectNumber="{ record }">
                        <div style="width:100%;height: 40px;">
                            <a-input-number v-model="record.defectNumber" class="input-demo" :min="0"
                                :max="1000000000000000000000000" />
                        </div>
                    </template>
                    <template #buttonMeterNum="{ record }">
                        <div style="width:100%;height: 40px;">
                            <a-input-number v-model="record.buttonMeterNum" class="input-demo" :min="0"
                                :max="1000000000000000000000000" />
                        </div>
                    </template>
                    <template #buttonMinuteNum="{ record }">
                        <div style="width:100%;height: 40px;">
                            <a-input-number v-model="record.buttonMinuteNum" class="input-demo" :min="0"
                                :max="1000000000000000000000000" />
                        </div>
                    </template>
                    <template #defectPlace="{ record }">
                        <div style="width:100%;height: 40px;">
                            <a-input v-model="record.defectPlace" />
                        </div>
                    </template>
                </a-table>
            </div>
            </div>
            
        </div>


        <a-drawer ok-text='保存' cancel-text='关闭' :mask-closable="false" :width="400" unmount-on-close
            style="z-index: 2;" :height="pageData.rHeight" :visible="pageData.showAdd"
            placement="bottom" @ok="sideOk" @cancel="pageData.showAdd = false">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form size="small" :model="pageData" layout="inline">
                    <a-form-item label="检验单号">
                        <a-input placeholder="" v-model="pageData.billNumber" />
                    </a-form-item>
                    <a-form-item label="检验日期">
                        <a-range-picker  popup-container="html"  v-model="pageData.billingDate"
                            style="width: 360px; margin-right: 24px; margin-bottom: 24px;" />
                    </a-form-item>
                    <a-form-item label="状态">
                        <a-input placeholder="" v-model="pageData.zt" />
                    </a-form-item>
                    <a-form-item label="织造序号">
                        <a-input placeholder="" v-model="pageData.weaveCode" />
                    </a-form-item>
                    <a-form-item label="计划单号">
                        <a-input placeholder="" v-model="pageData.planOrderCode" />
                    </a-form-item>
                    <a-form-item label="验布员工">
                        <a-input placeholder="" v-model="pageData.clothInspectorOne" />
                        <!-- <a-select popup-container="html"  :loading="loading" placeholder="请选择验布员工" @search="handleSearch"
                        v-model="pageData.dropDownData" :filter-option="false" allow-search allow-clear
                        @focus="focusSel">
                        <a-option v-for="item in pageData.DefectNameList" :value="item['clothInspectorOne']">{{
                                item["clothInspectorOne"]
                        }}</a-option>
                    </a-select> -->
                    </a-form-item>
                </a-form>
                <div style="text-align: right;">
                    <a-space style="margin-bottom:10px;">
                        <a-button type="primary" @click="cxLine" size="small" :disabled="!pageData.isCx">查询</a-button>
                        <a-button type="primary" @click="dcLine" size="small" :disabled="!pageData.isDc">导出</a-button>
                    </a-space>
                </div>

                <a-tabs   :lazy-load="true" :default-active-key="pageData.keysNum">
                    <!-- 验布检验列表 -->

                    <a-tab-pane :key="1" title="验布检验列表">

                        <a-table stripe :bordered="true" :columns="tableColumns"
                            :row-selection="{ showCheckedAll: true, width: 50 }" v-model:selected-keys="selectedRowKeys"
                            :loading="table.tableLoading" :data="dataForm.dataList" :rowKey="rowKey">

                        </a-table>
                    </a-tab-pane>
                    <!-- 计划单检验列表 -->
                    <a-tab-pane :key="2" title="计划单检验列表">

                        <a-table stripe :bordered="true" :columns="tableColumnsJhd"
                            :row-selection="{ showCheckedAll: true, width: 50 }" v-model:selected-keys="s"
                            :loading="table.tableLoading" :data="dataForm.jhdList" rowKey="loomCode">

                        </a-table>
                    </a-tab-pane>
                    <!-- 疵点问题记录 -->
                    <a-tab-pane :key="3" title="疵点问题记录">
                        <a-table stripe :bordered="true" :columns="tableColumnsCd"
                            :row-selection="{ showCheckedAll: true, width: 50 }" v-model:selected-keys="s1"
                            :loading="table.tableLoading" :data="dataForm.CdList" rowKey="barCode">
                            <template #perchingGrade="{ record }">
                                <a-select popup-container="html"  :loading="loading" placeholder="" @search="handleSearch"
                                    v-model="dataForm.form.perchingGrade" :filter-option="false" allow-search
                                    allow-clear @focus="focusSel"
                                    v-if="pageData.clothInspectorOne == record.clothInspectorOne">
                                    <a-option v-for="item in pageData.perchingGradeList"
                                        :value="item['verifyclothLevel']">
                                        {{ item["verifyclothLevel"] }}</a-option>
                                </a-select>
                            </template>
                            <template #edit="{ record }">
                                <a-button type="primary" size="small" status="warning"
                                    v-if="pageData.clothInspectorOne == record.clothInspectorOne"
                                    @click="editHandler(record)" :disabled="!pageData.isEdit">
                                    <template #icon>
                                        <icon-edit />
                                    </template>
                                    修 改
                                </a-button>
                            </template>
                        </a-table>
                    </a-tab-pane>

                </a-tabs>
            </div>
        </a-drawer>
    </div>
</template>

<script lang="ts">
import { post } from "@/api/http";
import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
} from "@/hooks/table";

import { ref, reactive, onMounted, onActivated, onUnmounted } from "vue";
import Toolbar from "@/components/Toolbar.vue";
import { Form, Message, Modal } from "@arco-design/web-vue";
import { FormInstance } from "@arco-design/web-vue/es/form";
import emitter from "@/hooks/useEventBus";
import validate from "@/hooks/useValidate";
import { DatasetComponent } from "echarts/components";
import { baseURL } from '../../../api/axios.config'
import axios from "axios";
import dayjs from 'dayjs';
import { InputInstance } from "@arco-design/web-vue/es/input";
import usePermission from '@/store/modules/permission'
interface DefectName {
    "id": any
    "jbzs": number | undefined
    "date": any[]
    "zzs": number | undefined
    "ybzl": number | undefined
    "form": any
    "yhzl": number | undefined
    "yg": any[]
    "ckList": any[]
    "dataList": any[]
    "jhdList": any[]
    "CdList": any[]
    "ygNameList": any[]
    "totalRevolutions": string | undefined
    "numberShifts": string | undefined
    "storageState": number | undefined
    "type": number | undefined
    "checkoutState": number | undefined
}
export default {
    name: "ScanningGreyCloth1",
    setup() {
        //查询 表单和左下角表
        const scrollbar = ref(true)
        function doRefresh() {
            pageData.pageLoading = true

            post({
                url: "qms/scannedGreyCloth/selectBuFei",
                data: dataForm.form.clothCode

            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        dataForm.yg = data.clothfiy;
                        dataForm.ygNameList = data.perchingRecord;
                        dataForm.form = data.scannedGreyCloth;//里面有个clothCode是扫飞布条码出来的 扫布飞要保存起来
                        dataForm.type = data.type
                        // table.handleSuccess(data.list);
                        // pagination.setTotalSize(data.total);

                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }
        //查询列表数据
        const cxLine = () => {
            post({
                url: "qms/scannedGreyCloth/select",
                data: {
                    "scannedGreyCloth":
                    {

                        "clothInspectorOne": "a"

                    }
                    ,
                    "perching": {
                        "planOrderCode": pageData.planOrderCode,
                        "weaveCode": pageData.weaveCode
                    },
                    "planOrder": {
                        "billNumber": pageData.billNumber,
                        // "billDateKs": pageData.billingDate.join(",")[0],
                        // "billDateJs": pageData.billingDate.join(",")[1],
                        "billDateKs": "",
                        "billDateJs": "",
                        "zt": pageData.zt
                    }
                }
            }).then(({ data, code, message }: any) => {
                if (code === 200) {
                    dataForm.dataList = data.perching
                    dataForm.jhdList = data.planOrder
                    dataForm.CdList = data.scannedGreyCloth
                } else {
                    Message.error({
                        content: message,
                        duration: 5000,
                    });
                }
            });
        }

        //两个主表
        const selectedRowKeysYg = useRowSelection();
        const selectedRowKeysCk = useRowSelection();
        //弹窗表格
        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const selectedRowKeysJhd = useRowSelection();
        const selectedRowKeysCd = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        //员工表
        const tableColumnsYg = useTableColumn([
            {
                title: "值机员工编号",
                key: "checkStaffCode",
                dataIndex: "checkStaffCode",
                width: 70
            },
            {
                title: "值机员工",
                key: "checkStaff",
                dataIndex: "checkStaff",
                width: 70
            },
            {
                title: "班次",
                key: "shift",
                dataIndex: "shift",
                width: 70
            },
            {
                title: "值机重量",
                key: "checkWeight",
                dataIndex: "checkWeight",
                width: 70
            },
            {
                title: "值机转数",
                key: "checkRevolution",
                dataIndex: "checkRevolution",
                width: 70
            },
            {
                title: "次布重量",
                key: "fabricWeight",
                dataIndex: "fabricWeight",
                width: 70
            },

        ]);
        //仓库表
        const tableColumnsCk = useTableColumn([
            {
                title: "值机员工编号",
                key: "checkStaffCode",
                dataIndex: "checkStaffCode",
                width: 70
            },
            {
                title: "值机员工",
                key: "checkStaff",
                dataIndex: "checkStaff",
                width: 70
            },
            {
                title: "疵点名称",
                key: "defectName",
                dataIndex: "defectName",
                width: 70
            },
            {
                title: "疵点个数",
                key: "defectNumber",
                dataIndex: "defectNumber",
                width: 70,
                slotName: 'defectNumber'
            },
            {
                title: "扣米数",
                key: "buttonMeterNum",
                dataIndex: "buttonMeterNum",
                width: 70,
                slotName: 'buttonMeterNum'
            },
            {
                title: "扣分数",
                key: "buttonMinuteNum",
                dataIndex: "buttonMinuteNum",
                width:70,
                slotName: 'buttonMinuteNum'
            },
            {
                title: "疵点位置",
                key: "defectPlace",
                dataIndex: "defectPlace",
                width: 70,
                slotName: 'defectPlace'
            },

        ]);
        //验布检验列表
        const tableColumns = useTableColumn([
            {
                title: "序号",
                key: "id",
                dataIndex: "id",
                width: 100
            },
            {
                title: "检验单号",
                key: "billNumber",
                dataIndex: "billNumber",
                width:100
            },
            {
                title: "坯布编码",
                key: "defectGrade",
                dataIndex: "defectGrade",
                width: 100
            },
            {
                title: "坯布名称",
                key: "greigeName",
                dataIndex: "greigeName",
                width: 100
            },
            {
                title: "规格",
                key: "specification",
                dataIndex: "specification",
                width: 100
            },
            {
                title: "品牌",
                key: "brand",
                dataIndex: "brand",
                width: 100
            },
            {
                title: "分类",
                key: "classify",
                dataIndex: "classify",
                width: 100
            },
            {
                title: "布号",
                key: "bigClothMark",
                dataIndex: "bigClothMark",
                width: 100
            },
            {
                title: "等级",
                key: "perchingGrade",
                dataIndex: "perchingGrade",
                width: 100
            },
            {
                title: "面料种类",
                key: "liningType",
                dataIndex: "liningType",
                width: 100
            },
            {
                title: "颜色",
                key: "colour",
                dataIndex: "colour",
                width: 100
            },
            {
                title: "纱支",
                key: "yarn",
                dataIndex: "yarn",
                width: 100
            },
            {
                title: "是否抽针",
                key: "needleNot",
                dataIndex: "needleNot",
                width: 100
            },
            {
                title: "是否开幅",
                key: "openNot",
                dataIndex: "openNot",
                width: 100
            },
            {
                title: "是否氨纶",
                key: "spandexNot",
                dataIndex: "spandexNot",
                width: 100
            },
        ]);
        //计划单检验列表
        const tableColumnsJhd = useTableColumn([
            {
                title: "织造序号",
                key: "weavingSerialNumber",
                dataIndex: "weavingSerialNumber",
                width: 100
            },
            {
                title: "指令重量",
                key: "orderWeight",
                dataIndex: "orderWeight",
                width: 100
            },
            {
                title: "机台名称",
                key: "machineName",
                dataIndex: "machineName",
                width: 100
            },
            {
                title: "计划单号",
                key: "planOrderCode",
                dataIndex: "planOrderCode",
                width: 100,
            },

            {
                title: "库存单位",
                key: "greyUnitName",
                dataIndex: "greyUnitName",
                width: 100
            },
            {
                title: "匹号",
                key: "horses",
                dataIndex: "horses",
                width: 100
            },
            {
                title: "落布重量",
                key: "croppingWeight",
                dataIndex: "croppingWeight",
                width: 100
            },
            {
                title: "验后重量",
                key: "posteriorWeight",
                dataIndex: "posteriorWeight",
                width: 100
            },
            {
                title: "次布重量",
                key: "fabricWeight",
                dataIndex: "fabricWeight",
                width: 100
            },
            {
                title: "次布转数",
                key: "fabricNun",
                dataIndex: "fabricNun",
                width: 100
            },
            {
                title: "验布时间",
                key: "billDate",
                dataIndex: "billDate",
                width: 100
            },
            {
                title: "值机员工",
                key: "checkStaff",
                dataIndex: "checkStaff",
                width: 100
            },
            {
                title: "值机重量",
                key: "checkWeight",
                dataIndex: "checkWeight",
                width: 100
            },
            {
                title: "值机转数",
                key: "checkRevolution",
                dataIndex: "checkRevolution",
                width: 100
            },
        ]);
        //疵点问题记录
        const tableColumnsCd = useTableColumn([
            {
                title: "疵点名称",
                key: "defectName",
                dataIndex: "defectName",
                width: 100
            },
            {
                title: "疵点个数",
                key: "defectNumber",
                dataIndex: "defectNumber",
                width: 100
            },
            {
                title: "验布员",
                key: "clothInspectorOne",
                dataIndex: "clothInspectorOne",
                width: 100
            },
            {
                title: "检验日期",
                key: "checkoutDate",
                dataIndex: "checkoutDate",
                width: 100,
            },
            {
                title: "布飞条码号",
                key: "barCode",
                dataIndex: "barCode",
                width: 100
            },
            {
                title: "验布条数",
                key: "ybNum",
                dataIndex: "ybNum",
                width: 100
            },
            {
                title: "班长复检",
                key: "monitorRetest",
                dataIndex: "monitorRetest",
                width: 100
            },
            {
                title: "复检日期",
                key: "retestDate",
                dataIndex: "retestDate",
                width: 100
            },
            {
                title: "客户名称",
                key: "client",
                dataIndex: "client",
                width: 100
            },
            {
                title: "批量更新验布等级",
                key: "perchingGrade",
                dataIndex: "perchingGrade",
                width: 100,
                slotName: 'perchingGrade'
            },
            {
                title: "验布时间",
                key: "ybTime",
                dataIndex: "ybTime",
                width: 100
            },
            {
                title: "编辑",
                key: "edit",
                dataIndex: "edit",
                slotName: 'edit',
                width: 100, fixed: 'right'
            }

        ]);
        const scroll = {
            x: 2000,
            y: 200
        };
        const tablediv = ref(null)
        const pageData = reactive<{
            DefectName: DefectName[]
            showAdd: boolean
            sideTitle: string
            dropDownData: any
            pageLoading: boolean,
            height: number,
            tablediv: any,
            rHeight: number | undefined,
            rHeight1: number | undefined,
            DefectNameList: [],
            isDisable: boolean,
            keysNum: any,
            defectNameList: any[],
            defectOb: any[],
            clickDefectOb: any[],
            ckTableInfo: {},
            ygList: [],
            perchingGradeList: any[],
            getCkList: any[],
            warehouseName: string | undefined,
            btnText: string | undefined,
            clothInspectorOne: string | undefined,
            planOrderCode: string | undefined,
            weaveCode: string | undefined,
            billNumber: string | undefined,
            zt: any,
            billingDate: any[]
            clothWarehouse: number | undefined
            retestDate: any
            monitorRetest: string | undefined,
            dropDownData1: string | undefined,
            isEdit: boolean | undefined,
            isSave: boolean | undefined,
            isJd: boolean | undefined,
            isXb: boolean | undefined,
            isScan: boolean | undefined,
            isLook: boolean | undefined,
            isCx: boolean | undefined,
            isDc: boolean | undefined,
        }>({
            DefectName: [],
            showAdd: false,
            sideTitle: "查看验布历史记录",
            dropDownData: "",
            pageLoading: false,
            height: 0,
            tablediv: null,
            rHeight: 0,
            DefectNameList: [],
            isDisable: false,
            keysNum: 1,
            rHeight1: 0,
            defectNameList: [],
            defectOb: [],
            clickDefectOb: [],
            ckTableInfo: {},
            ygList: [],
            perchingGradeList: [],
            getCkList: [],
            warehouseName: "",
            btnText: "关闭",
            clothInspectorOne: "",
            planOrderCode: "",
            weaveCode: "",
            billNumber: "",
            zt: "",
            billingDate: [],
            clothWarehouse: 1,
            retestDate: "",
            monitorRetest: "",
            dropDownData1: "",
            isEdit: false,
            isSave: false,
            isJd: false,
            isXb: false,
            isScan: false,
            isLook: false,
            isCx: false,
            isDc: false,
        });
        //下拉框得到焦点
        const focusSel = () => {
            selCxAll({ "verifyclothLevel": "" })
        }
        //下拉数据 
        const options = ref<any>(pageData.perchingGradeList);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { verifyclothLevel: value }
                loading.value = true;
                window.setTimeout(() => {
                    selCxAll(ob);
                    options.value = pageData.perchingGradeList;
                    loading.value = false;
                }, 200)
            } else {
                options.value = []
            }
        };
        //下拉框查询
        function selCxAll(val: any) {
            post({
                url: "qms/verifyClothLevel/VerifyclothLevelValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    // (data as string[]).splice(0, 0, "全部");
                    pageData.perchingGradeList = data;

                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }

        onMounted(() => {
            cxAllDefectName()
            // doRefresh();
            getFocus.value?.focus();

            emitter.on("refresh-ScanningGreyCloth", () => {
                getFocus.value?.focus();
                cxAllDefectName();
                // doRefresh();
            });
            pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight

            //弹出层的高
            if (pageData.rHeight !== undefined) {
                pageData.rHeight = pageData.rHeight - 100;
            }
            window.addEventListener('resize', () => {
                pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
                //弹出层的高
                if (pageData.rHeight !== undefined) {
                    pageData.rHeight = pageData.rHeight - 100;
                }
            })
            //按下f3清空所有数据
            document.onkeydown = function (ev) {
                var event: any = ev || event
                if (event.keyCode == 114) {
                    dataForm.date = [];
                    dataForm.form = {};
                    dataForm.yg = [];
                    dataForm.ckList = [];
                    dataForm.dataList = [];
                    dataForm.jhdList = [];
                    dataForm.CdList = [];
                    dataForm.ygNameList = [];
                }
            };
        });


        //查询所有疵点名称
        function cxAllDefectName() {
            post({
                url: "qms/defectType/select",
                data: { "defectName": "" }
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    // (data as string[]).splice(0, 0, "全部");
                    pageData.defectNameList = data;

                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }
        //查看历史记录
        const viewHistory = () => {

            pageData.showAdd = true;
            pageData.sideTitle = "查看验布历史记录";
            pageData.isEdit = false;
        };
        const dataForm = reactive<DefectName>({
            "id": null,
            "jbzs": 0,
            "date": [],
            "zzs": 0,
            "ybzl": 0,
            "form": {},
            "yhzl": 0,
            "yg": [],
            "ckList": [],
            "dataList": [],
            "jhdList": [],
            "CdList": [],
            "ygNameList": [],
            "numberShifts": "",
            "totalRevolutions": "",
            "storageState": 0,
            "type": 0,
            "checkoutState": 0,

        });
        const formRef = ref<FormInstance>();
        const sideOk = () => {
            var dataOb: any = [];
            dataForm.CdList.forEach(function (o: any) {
                var ob = {};
                ob["perchingGrade"] = o["perchingGrade"]
                ob["id"] = o["id"]
                dataOb.push(ob)
            })
            formRef.value?.validate().then((err) => {

                post({
                    url: "qms/scannedGreyCloth/newUpdate",
                    data: dataOb,
                }).then((res: any) => {
                    if (res.code === 200) {

                        formRef.value?.resetFields();

                        pageData.showAdd = false;

                        Message.success({
                            content: "保存成功",
                            duration: 5000,
                        });
                        doRefresh();
                    } else {
                        Message.error({
                            content: res.message,
                            duration: 5000,
                        });
                    }

                });

            });
        };


        //保存
        const saveHandler = () => {
            dataForm.yg.forEach(function (o) {
                o["totalRevolutions"] = dataForm.totalRevolutions
                o["totalRevolutions"] = dataForm.numberShifts
                o["storageState"] = dataForm.storageState
                o["checkoutState"] = dataForm.checkoutState
            })
            post({
                url: "qms/scannedGreyCloth/insert",
                data: {
                    "scannedGreyCloth": dataForm.form,
                    "perchingRecord": dataForm.yg,
                    "abnormal": dataForm.ckList
                },
            }).then(({ code, data, message }: any) => {
                if (code === 200) {
                    Message.success({
                        content: "保存成功",
                        duration: 5000,
                    });
                    doRefresh()
                } else {
                    Message.error({
                        content: message,
                        duration: 5000,
                    });
                }

            });
        }
        //修补
        const repairHandler = () => {

            post({
                url: "qms/perchingAnomaly/insert",
                data: {
                    "scannedGreyCloth": dataForm.form,
                    "perchingRecord": dataForm.yg,
                    "abnormal": dataForm.ckList
                },
            }).then(({ code, data, message }: any) => {
                if (code === 200) {
                    Message.success({
                        content: "保存成功",
                        duration: 5000,
                    });
                    doRefresh()
                } else {
                    Message.error({
                        content: message,
                        duration: 5000,
                    });
                }

            });
        }
        //降等

        const downgradeHandler = () => {

            post({
                url: "qms/perchingAnomaly/insert",
                data: {
                    "scannedGreyCloth": dataForm.form,
                    "perchingRecord": dataForm.yg,
                    "abnormal": dataForm.ckList
                },
            }).then(({ code, data, message }: any) => {
                if (code === 200) {
                    Message.success({
                        content: "保存成功",
                        duration: 5000,
                    });
                    doRefresh()
                } else {
                    Message.error({
                        content: message,
                        duration: 5000,
                    });
                }

            });
        }
        //判断是否填写了中文
        const isChiese = (value: string, cb: Function) => {
            return new Promise<void>(resolve => {
                if (window.encodeURI(value).indexOf('%') !== -1) {
                    cb('填写的值只能是英文数字组合或英文，数字！')
                }
                resolve()
            })

        }
        //导出
        const dcLine = () => {
            if (selectedRowKeys.value.length === 0 && selectedRowKeysJhd.selectedRowKeys.value.length === 0 && selectedRowKeysCd.selectedRowKeys.value.length === 0) {
                Message.error('请先勾选')
                return
            } else {
                let head = "";
                let body = "";
                if (selectedRowKeys.value.length !== 0) {
                    //将表头拼接出来
                    head += "<th>序号</th><th>检验单号</th><th>坯布列表</th><th>坯布名称</th><th>规格</th><th>品牌</th><th>分类</th><th>布号</th><th>等级</th>" +
                        "<th>面料种类</th><th>颜色</th><th>纱支</th><th>是否抽针</th><th>是否开幅</th><th>是否氨纶</th>"
                    //验布检验列表
                    let nowRow = table.dataList.filter(function (o) {
                        return selectedRowKeys.value.indexOf(o["id"]) !== -1;
                    })
                    nowRow.forEach(function (o: any) {
                        body += "<tr>";
                        body += "<td>" + o["id"] + "</td>";
                        body += "<td>" + o["billNumber"] + "</td>";
                        body += "<td>" + o["defectGrade"] + "</td>";
                        body += "<td>" + o["greigeName"] + "</td>";
                        body += "<td>" + o["specification"] + "</td>";
                        body += "<td>" + o["brand"] + "</td>";
                        body += "<td>" + o["classify"] + "</td>";
                        body += "<td>" + o["bigClothMark"] + "</td>";
                        body += "<td>" + o["perchingGrade"] + "</td>";
                        body += "<td>" + o["liningType"] + "</td>";
                        body += "<td>" + o["colour"] + "</td>";
                        body += "<td>" + o["yarn"] + "</td>";
                        body += "<td>" + o["needleNot"] + "</td>";
                        body += "<td>" + o["openNot"] + "</td>";
                        body += "<td>" + o["spandexNot"] + "</td>";
                        body += "</tr>";
                    })
                } else if (selectedRowKeysJhd.selectedRowKeys.value.length === 0) {
                    head += "<th>织造序号</th><th>指令重量</th><th>机台名称</th>" +
                        "<th>计划单号</th><th>计划重量</th><th>库存单位</th><th>匹号</th><th>落布重量</th><th>验后重量</th><th>次布转数</th><th>验布时间</th><th>值机员工</th>" +
                        "<th>值机重量</th><th>值机转数</th>"
                    //计划单
                    let jhdRow = dataForm.jhdList.filter(function (o) {
                        return selectedRowKeysJhd.selectedRowKeys.value.indexOf(o["loomCode"]) !== -1;
                    })
                    jhdRow.forEach(function (o: any) {
                        body += "<tr>";
                        body += "<td>" + o["loomCode"] + "</td>";
                        body += "<td>" + o["weaveOdd"] + "</td>";
                        body += "<td>" + o["defectGrade"] + "</td>";
                        body += "<td>" + o["deleteDonation"] + "</td>";
                        body += "<td>" + o["perchingGrade"] + "</td>";
                        body += "<td>" + o["perchingGrade"] + "</td>";
                        body += "<td>" + o["perchingGrade"] + "</td>";
                        body += "<td>" + o["perchingGrade"] + "</td>";
                        body += "<td>" + o["perchingGrade"] + "</td>";
                        body += "<td>" + o["perchingGrade"] + "</td>";
                        body += "<td>" + o["perchingGrade"] + "</td>";
                        body += "<td>" + o["perchingGrade"] + "</td>";
                        body += "<td>" + o["perchingGrade"] + "</td>";
                        body += "<td>" + o["perchingGrade"] + "</td>";
                        body += "<td>" + o["perchingGrade"] + "</td>";
                        body += "</tr>";
                    })
                } else if (selectedRowKeysCd.selectedRowKeys.value.length === 0) {
                    head += "<th>疵点名称</th><th>疵点个数</th><th>验布员</th><th>检验日期</th><th>布飞条码号</th><th>验布条数</th><th>班长复检</th>" +
                        "<th>复检日期</th><th>客户名称</th><th>批量更新验布等级</th><th>验布时间</th>"

                    //疵点
                    let cdRow = dataForm.CdList.filter(function (o) {
                        return selectedRowKeysCd.selectedRowKeys.value.indexOf(o["barCode"]) !== -1;
                    })
                    cdRow.forEach(function (o: any) {
                        body += "<tr>";
                        body += "<td>" + o["defectName"] + "</td>";
                        body += "<td>" + o["defectNumber"] + "</td>";
                        body += "<td>" + o["clothInspectorOne"] + "</td>";
                        body += "<td>" + o["checkoutDate"] + "</td>";
                        body += "<td>" + o["barCode"] + "</td>";
                        body += "<td>" + o["ybNum"] + "</td>";
                        body += "<td>" + o["monitorRetest"] + "</td>";
                        body += "<td>" + o["retestDate"] + "</td>";
                        body += "<td>" + o["client"] + "</td>";
                        body += "<td>" + o["perchingGrade"] + "</td>";
                        body += "<td>" + o["ybTime"] + "</td>";

                        body += "</tr>";
                    })
                }




                tableToXlsx(head, '疵点名称', body)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

            const a = document.createElement('a');
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
            a.download = filename;
            a.click();
            document.removeChild(a);
        }
        //模板下载
        const downloadHandler = () => {
            window.open(baseURL + '/product/mercery/uploadMerceryModel')
        }
        //导入
        const importHandler = () => {

            const inputEle: HTMLInputElement = document.createElement('input')
            inputEle.type = 'file'
            inputEle.id = 'fileUploadExcel'
            inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
            inputEle.addEventListener('change', (e) => {
                const formData = new FormData()
                if (inputEle.files !== null) {
                    formData.append('file', inputEle.files[0] || '')
                } else {
                    Message.warning('未选择文件！');
                    return
                }
                pageData.pageLoading = true
                axios.post(baseURL + '/qms/clothtype/uploadModel', formData, {
                    headers: {
                        "Content-Type": 'multipart/form-data',
                        "token": sessionStorage.getItem('USER-TOKEN-KEY')
                    },
                }).then((result) => {
                    if (result.data['code'] === 200) {
                        Message.success('导入成功')
                    } else {
                        Message.error(result.data.message)
                    }

                }).finally(() => {
                    pageData.pageLoading = false
                    doRefresh()
                })
            })
            inputEle.click()
        }
        //布飞弹出框的方法
        const visible = ref(false);
        const getFocus = ref<InputInstance | null>(null);
        var defectName = "";
        const handleClick = (name: any) => {
            visible.value = true;
            defectName = name;

        };
        const handleBeforeOk = (done: any) => {
            done()

        };
        const handleCancel = () => {
            visible.value = false;
        }
        //点击员工 加行数
        const clickName = (name: any, code: any) => {
            const list: any = [];
            let isExist = false;
            dataForm.ckList.forEach(function (o) {
                //行里有相同的员工和疵点名称 此行的疵点个数就加一
                if (o["checkStaff"] == name && o["defectName"] == defectName) {
                    o["defectNumber"]++;
                    isExist = true;
                }
            })
            if (!isExist) {
                const ob = {
                    "checkStaff": name,
                    "checkStaffCode": code,
                    "defectName": defectName,
                    "defectNumber": 1,
                    "buttonMeterNum": 0,
                    "buttonMinuteNum": 0,
                    "defectPlace": ""
                }
                list.push(ob)
            }
            if (list.length > 0) {
                for (let i = 0; i < list.length; i++) {
                    dataForm.ckList.unshift(list[i])
                }
            }

        }
        // //点击弹出框
        // const visible1 = ref(false);
        // const clickTag = (defectName: any) => {
        //     visible1.value = true;
        // }
        // const handleBeforeOk1 = (done: any) => {
        //     done()
        // };
        // const handleCancel1 = () => {
        //     visible1.value = false;
        // }
        //表单显示隐藏
        let isShow = ref(true);
        //布飞条码的值
        const changeTm = (val: any) => {
            // isShow.value = false
            dataForm.form.clothCode = JSON.parse(val)
            console.log(dataForm.form.clothCode);
            dataForm.form.clothCode["firm"] = decodeURI(dataForm.form.clothCode["firm"])
            if (dataForm.form['greyCode'] == undefined) {
                dataForm.form['greyCode'] = ""
                dataForm.form['greyCode'] = dataForm.form.clothCode['greyCode']
            }
            if (dataForm.form['machineCode'] == undefined) {
                dataForm.form['machineCode'] = ""
                dataForm.form['machineCode'] = dataForm.form.clothCode['machineCode']
            }
            if (dataForm.form['bigClothMark'] == undefined) {
                dataForm.form['bigClothMark'] = ""
                dataForm.form['bigClothMark'] = dataForm.form.clothCode['bigClothMark']
            }

            doRefresh()
        }
        const openPop = () => {
            isShow.value = !isShow.value;
            if (isShow.value) {
                pageData.btnText = "关闭"
            } else {
                pageData.btnText = "显示"
            }



        }
        //关闭弹窗按钮
        // const closeHandler = () => {
        //     isShow.value = false;
        // }

        //下拉框得到焦点
        const focusSel1 = () => {
            selCxAll1({
                "firm": "掌紫元8",
                "warehouseName": "次布仓",
                "warehouseTypeName": "次布仓",
            })
        }
        //下拉数据 
        const options1 = ref<any>(pageData.getCkList);
        const loading1 = ref(false);
        const handleSearch1 = (value: any) => {
            if (value) {
                const ob = {
                    "firm": "掌紫元8",
                    "warehouseName": "次布仓",
                    "warehouseTypeName": "次布仓",
                    "virtuallyState":0
                }
                loading1.value = true;
                window.setTimeout(() => {
                    selCxAll1(ob);
                    options1.value = pageData.getCkList;
                    loading1.value = false;
                }, 200)
            } else {
                options1.value = []
            }
        };
        //获取仓库下拉框
        function selCxAll1(ob: any) {
            post({
                url: "wms/warehouse/getWarehouseByPara",
                data: ob
            }).then(({ code, data, message }: any) => {
                if (code === 200) {
                    pageData.getCkList = data;
                } else {
                    Message.error({
                        content: message,
                        duration: 5000,
                    });
                }

            });
        }
        const changeClothWarehouse = (value: any, ev: any) => {
            if (value) {
                pageData.clothWarehouse = 1
            } else {
                pageData.clothWarehouse = 0
            }

        }
        //点击编辑 疵点列表可修改
        const editHandler = (rowData: any) => {
            pageData.isEdit = true;
            dataForm.form.perchingGrade = rowData.perchingGrade;
        }
        //设置权限
        // ['查询', '新增', '删除', '导出', '导入']
        const permissionStore = usePermission()

        if (permissionStore.hasPermisson('smpb.pbsm')) {
            pageData.isScan = true;
        }
        if (permissionStore.hasPermisson('smpb.bc')) {
            pageData.isSave = true;
        }
        if (permissionStore.hasPermisson('smpb.xb')) {
            pageData.isXb = true;
        }
        if (permissionStore.hasPermisson('smpb.jd')) {
            pageData.isJd = true;
        }
        if (permissionStore.hasPermisson('smpb.ckls')) {
            pageData.isLook = true;
        }
        if (permissionStore.hasPermisson('smpb-ckls.cx')) {
            pageData.isCx = true;
        }
        if (permissionStore.hasPermisson('smpb-ckls.dc')) {
            pageData.isDc = true;
        }
        return {
            scroll,
            scrollbar,
            tablediv,
            downloadHandler,
            importHandler,
            sideOk,
            formRef,
            dataForm,
            viewHistory,
            selectedRowKeys,
            tableColumns,
            tableColumnsJhd,
            tableColumnsCd,
            tableColumnsYg,
            tableColumnsCk,
            pagination,
            dayjs,
            table,
            rowKey,
            pageData,
            options,
            loading,
            handleSearch,
            options1,
            loading1,
            handleSearch1,
            focusSel1,
            isChiese,
            focusSel,
            s: selectedRowKeysJhd.selectedRowKeys,
            s1: selectedRowKeysCd.selectedRowKeys,
            z: selectedRowKeysYg.selectedRowKeys,
            z1: selectedRowKeysCk.selectedRowKeys,
            visible,
            handleClick,
            handleBeforeOk,
            getFocus,
            handleCancel,
            // clickTag,
            // visible1,
            // handleBeforeOk1,
            // handleCancel1,
            isShow,
            changeTm,
            openPop,
            // closeHandler,
            saveHandler,
            clickName,
            defectName,
            repairHandler,
            downgradeHandler,
            cxLine,
            changeClothWarehouse,
            dcLine,
            editHandler
        };
    },
    components: { Toolbar },
};
</script>
<style scoped lang="less">
.active {
    background-color: #00b42a;
}
*{
    box-sizing: border-box !important;
}
</style>
